import { Upload } from "antd";
import ImgCrop from "antd-img-crop";
import { useQiniu } from "pages/label/util";
import {
  UploadFile,
  UploadChangeParam,
  UploadProps,
} from "antd/lib/upload/interface";
import { ImgCropProps } from "antd-img-crop/index";
import { useState } from "react";
import { useEffect } from "react";

type ImageUploadProps = UploadProps &
  Omit<ImgCropProps, "children"> & {
    value: UploadFile[];
    onChange: (info: UploadChangeParam<UploadFile<any>>) => void;
    nums: number;
  };

export const UploadImage = (props: ImageUploadProps) => {
  const { value, onChange, nums, modalTitle, modalWidth, aspect } = props;
  const [fileList, setFileList] = useState<UploadFile[]>([]);

  useEffect(() => {
    setFileList(value);
  }, [value]);

  const onPreview = async (file: any) => {
    let src = file.url;
    if (!src) {
      src = await new Promise((resolve) => {
        const reader = new FileReader();
        reader.readAsDataURL(file.originFileObj);
        reader.onload = () => resolve(reader.result);
      });
    }
    const image = new Image();
    image.src = src;
    const imgWindow = window.open(src);
    imgWindow?.document.write(image.outerHTML);
  };

  const { data } = useQiniu();
  // setFileList(value);

  const onChangeImg = (info: UploadChangeParam<UploadFile<any>>) => {
    setFileList(info.fileList);
    onChange(info);
  };

  const getUploadToken = () => {
    return {
      token: data?.token,
    };
  };

  return (
    <ImgCrop
      aspect={aspect}
      rotate
      modalTitle={modalTitle}
      modalWidth={modalWidth}
    >
      <Upload
        action="http://upload.qiniu.com"
        listType="picture-card"
        fileList={fileList}
        data={getUploadToken}
        onChange={onChangeImg}
        onPreview={onPreview}
      >
        {fileList.length < nums && "+ Upload"}
      </Upload>
    </ImgCrop>
  );
};
